package com.qf.drop.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qf.common.core.config.ThreadPoolConfig;
import com.qf.common.core.entity.DropOrder;
import com.qf.common.pay.param.PayFinishParam;
import com.qf.drop.mapper.DropOrderMapper;
import com.qf.drop.service.DropOrderService;
import com.qf.pay.param.PayStatusParam;
import com.qf.pay.service.OrderPayService;
import com.qf.recharge.service.RechargeService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zdl
 * @date 2025/4/3
 */
@Service
public class DropOrderServiceImpl implements DropOrderService {
    @Resource
    private DropOrderMapper dropOrderMapper;

    @Lazy
    @Resource
    private OrderPayService orderPayService;

    @Resource
    private ThreadPoolConfig threadPoolConfig;

    @Resource
    private RechargeService rechargeService;

    @Override
    public void addDropOrder(DropOrder dropOrder) {
        dropOrderMapper.insert(dropOrder);
    }

    @Override
    public void dropOrderTask() {
        List<DropOrder> dropOrders = dropOrderMapper.selectList(null);
        dropOrders.forEach(item -> {
            threadPoolConfig.taskExecutor().execute(() -> {
                PayStatusParam ret = orderPayService.checkPayStatus(item.getOrderNo(), item.getNum());
                if (ret.getStatus().equals(1) || ret.getStatus().equals(3)) {
                    // 删除数据
                    dropOrderMapper.delete(new LambdaUpdateWrapper<DropOrder>()
                            .eq(DropOrder::getOrderNo, item.getOrderNo()));
                    if (ret.getStatus().equals(1)) {
                        // 支付成功
                        PayFinishParam param = new PayFinishParam();
                        param.setOrderNo(item.getOrderNo());
                        param.setTradeNo(ret.getTradeNo());
                        rechargeService.updateRecharge(param);
                    }
                } else {
                    // 更新轮询次数
                    dropOrderMapper.update(null, new LambdaUpdateWrapper<DropOrder>()
                            .eq(DropOrder::getOrderNo, item.getOrderNo())
                            .set(DropOrder::getNum, item.getNum() + 1));
                }
            });

        });
    }
}
